package com.heima.search.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.UserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 删除搜索历史
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult deleteUserSearch(HistorySearchDto dto) {
        //检查参数
        if(dto == null || dto.getId() ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否登录
        Integer userId = UserThreadLocalUtil.getUser();
        if(userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        mongoTemplate.remove(Query.query(Criteria.where("userId").is(userId)
                .and("id").is(dto.getId())), ApUserSearch.class);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询搜索历史
     *
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {
        log.info("【查询历史搜索 --- begin】");
        log.info("获取当前用户");
        Integer userId = UserThreadLocalUtil.getUser();
        if(userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //获取历史查询列表
        List<ApUserSearch> userSearchList = mongoTemplate.find(Query.query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class);
        log.info("【查询结果】:{}",userSearchList);
        log.info("【查询历史搜索 --- end】");
        return ResponseResult.okResult(userSearchList);

    }

    /**
     * 保存用户搜索历史记录
     *
     * @param keyword
     * @param userId
     */
    @Override
    @Async
    public void insert(String keyword, Integer userId) {
        log.info("【搜索历史记录】--- begin");
        //1.查询当前用户的搜索关键词
        log.info("【检查参数】keyword:{},userId:{}",keyword, userId);
        Query query = Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
        ApUserSearch userSearch = mongoTemplate.findOne(query, ApUserSearch.class);

        //2.存在 更新创建时间
        if(userSearch != null){
            log.info("【关键词存在】");
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
            return;
        }
        //3.不存在，判断当前历史记录总数量是否超过10
        log.info("【关键词不存在】");
        userSearch = new ApUserSearch();
        userSearch.setUserId(userId);
        userSearch.setKeyword(keyword);
        userSearch.setCreatedTime(new Date());

        Query query1 = Query.query(Criteria.where("userId").is(userId));
        query1.with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> userSearchList = mongoTemplate.find(query1, ApUserSearch.class);
        log.info("【用户搜索记录】:{}",userSearchList);
        if(userSearchList.size() < 10){
            mongoTemplate.save(userSearch);
        }else{
            ApUserSearch lastUserSearch = userSearchList.get(userSearchList.size()-1);
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(lastUserSearch.getId())), userSearch);
        }
        log.info("【搜索历史记录】--- end");

    }
}
